import axios from 'axios';
import Qs from 'qs';
import {router} from '../router/index';
import Cookies from 'js-cookie';
import { httpUrl } from './httpUrl';

const JSON_TYPE = 'json';
const FORM_CONFIG = {
    transformRequest: [function (data) {
        data = Qs.stringify(data);
        return data;
    }],
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    // headers: {'Content-Type': 'application/form-data'}
};
const JSON_CONFIG = {
    transformRequest: [function (data) {
        let standardJson = decodeURI(encodeURI(JSON.stringify(data)));
        return standardJson;
    }],
    headers: {'Content-Type': 'application/json'}
};

const ajax = axios.create({
    baseURL: httpUrl,
    transformRequest: [function (data) {
        data = Qs.stringify(data);
        return data;
    }],
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    timeout: 20000
});

ajax.interceptors.response.use(
    function (response) {
        if (response.data.status === 'auth-1001' || response.data.status === 'auth-1000' || response.data.status === 'auth-1003') {
            localStorage.clear();
            Cookies.set('locking', '0');
            router.push('/login');
            response.data.message = '登录信息失效，请重新登录！';
            return response.data;
        } else if (response.data.status === 'auth-1002') {
            router.push('/403');
            return response.data;
        } else if (response.data.status === '404') {
            router.push('/404');
            return response.data;
        } else {
            return response.data;
        }
    },
    function (error) {
        if (error.response) {
            let status = error.response.status;
            switch (status) {
                case 504:
                    error.message = '请求超时，请检查网络！';
                    break;
                case 500:
                    error.message = '服务器繁忙，请稍后再试！';
                    break;
                case 404:
                    error.message = '页面不存在！';
                    break;
                default:
                    error.message = '未知错误！';
            }
        }
        return Promise.reject(error);
    }
);

ajax.interceptors.request.use(
    function (config) {
        config.headers['token'] = localStorage.getItem('token');
        return config;
    },
    function (error) {
        return Promise.reject(error);
    }
);

/**
 * GET请求方法封
 * @param {*} url request url
 * @param {*} params param
 * @param {*} dataType
 */
export function get (url, params = {}, dataType) {
    return new Promise((resolve, reject) => {
        ajax.get(url,
            {params: params},
            dataType === JSON_TYPE ? JSON_CONFIG : ''
        ).then(res => {
            if (res.status === '0') {
                resolve(res.data);
            } else {
                reject(res);
            }
        }).catch(error => {
            reject(error);
        });
    });
}

/**
 * POST请求方法封装
 * @param {*} url request url
 * @param {*} data
 * @param {*} dataType
 */
export function post (url, data = {}, dataType) {
    return new Promise((resolve, reject) => {
        ajax.post(
            url,
            data,
            dataType === JSON_TYPE ? JSON_CONFIG : ''
        ).then(res => {
            if (res.status === '0') {
                resolve(res.data);
            } else {
                reject(res);
            }
        }).catch(error => {
            reject(error);
        });
    });
}

/**
 * DELET方法
 */
export function del (url, data = {}, dataType) {
    return new Promise((resolve, reject) => {
        ajax.delete(
            url,
            {
                data: data,
                transformRequest: [function (data) {
                    let param;
                    if (dataType === JSON_TYPE) {
                        param = decodeURI(encodeURI(JSON.stringify(data)));
                    } else {
                        param = Qs.stringify(data);
                    }
                    return param;
                }],
                headers: dataType === JSON_TYPE ? {'Content-Type': 'application/json'} : ''
            }
        ).then(res => {
            if (res.status === '0') {
                resolve(res.data);
            } else {
                reject(res);
            }
        }).catch(error => {
            reject(error);
        });
    });
}
